const gatherServices = require('./gatherServices');
const WebSocket = require('ws');
const Device = require('../models/DeviceModel');
async function updateDeviceStatus(deviceName, newStatus) {
    try {
        const updatedDevice = await Device.findOneAndUpdate(
            { deviceName: deviceName }, // 查询条件
            { accountStatus: newStatus }, // 更新内容
            { new: true } // 返回更新后的文档
        );

        if (updatedDevice) {
            console.log('更新成功:', updatedDevice);
        } else {
            console.log('未找到该设备');
        }
    } catch (error) {
        console.error('更新失败:', error);
    }
}
async function updateDevicework(deviceName, newWork) {
    try {
        const updatedDevice = await Device.findOneAndUpdate(
            { deviceName: deviceName }, // 查询条件
            { work: newWork }, // 更新内容
            { new: true } // 返回更新后的文档
        );

        if (updatedDevice) {
            console.log('更新成功:', updatedDevice);
        } else {
            console.log('未找到该设备');
        }
    } catch (error) {
        console.error('更新失败:', error);
    }
}
class WebSocketService {
    constructor() {
        if (!WebSocketService.instance) {
            this.clients = new Map(); // 使用 Map 存储客户端
            WebSocketService.instance = this; // 保存实例
        }

        return WebSocketService.instance; // 返回单例实例
    }

    handleConnection(ws) {
        const clientId = Date.now(); // 生成唯一的客户端 ID
        this.clients.set(clientId, { ws, newClientId: null }); // 将客户端与 ID 关联，newClientId 默认为 null
        console.log(`New client connected: ${clientId}`);
        // console.log(this.clients);
        // 心跳检测
        ws.isAlive = true; // 标记连接为存活
        ws.on('pong', () => { ws.isAlive = true; }); // 收到 pong 时重置存活状态

        ws.on('message', (message) => {
            
            const data = JSON.parse(message);
            switch (data.type) {
                case 'accountInfo':
                    // 处理类型 1 的消息
                    this.handleMessage(data, clientId);
                    break;
                case 'initInfo':
                    // 处理类型 2 的消息
                    this.changeMessage(data, clientId);
                    break;
                
            }
            // this.handleMessage(data, clientId); // 传递 clientId

        });

        ws.on('close', () => {
            console.log(`Client disconnected: ${clientId}`);
            console.log("连接关闭")
            for (const [Id, Info] of this.clients) {
                console.log(Id,Info.newClientId)
                if (Id === clientId) {
                    console.log("更新状态")
                    updateDeviceStatus(Info.newClientId, '掉线');
                    updateDevicework(Info.newClientId, '无');
                    break; // 找到后返回
                }
            }
            // console.log("删除前",this.clients);
            this.clients.delete(clientId); // 从 Map 中删除客户端
            // console.log("删除后",this.clients);
        });

        ws.on('error', (error) => {
            console.error('WebSocket error:', error);
        });
    }
    changeMessage(data,clientId){
        for (const [Id, Info] of this.clients) {
            console.log(Id,Info.newClientId)
            if (Id === clientId) {
                console.log("更新状态")
                updateDeviceStatus(Info.newClientId, data.state);
                updateDevicework(Info.newClientId, '无');
                break; // 找到后返回
            }
        }
    }
    handleMessage(data, clientId) {
        // 添加账号事件
        if (data.type === 'accountInfo') {
            gatherServices.addGatherDevice(data);
            console.log(`New client data: ${JSON.stringify(data)}`);

            // 更新客户端 ID
            const newClientId = data.deviceName; // 假设 id 存在于 data.data 中
            if (newClientId) {
                const clientInfo = this.clients.get(clientId); // 获取当前客户端信息
                clientInfo.newClientId = newClientId; // 更新 newClientId
                console.log(`Client ID updated from ${clientId} to ${newClientId}`);
            }
        }
    }
    //传输
    sendMessage(newClientId, message) {
        // 找到对应的客户端连接
        for (const [clientId, clientInfo] of this.clients) {
            if (clientInfo.newClientId === newClientId) {
                const clientWs = clientInfo.ws;
                if (clientWs && clientWs.readyState === WebSocket.OPEN) {
                    updateDevicework(newClientId,message.data.taskParams);
                    clientWs.send(JSON.stringify(message));
                } else {
                    console.error(`Client ${newClientId} not connected or invalid.`);
                }
                return; // 找到后返回
            }
        }
        console.error(`Client with newClientId ${newClientId} not found.`);
    }

    // 心跳检测定时器
    startHeartbeat() {
        setInterval(() => {
            this.clients.forEach((clientInfo, clientId) => {
                if (clientInfo.ws.isAlive === false) {
                    console.log(`Terminating client: ${clientId}`);
                    Device.updateOne(
                        { deviceName: clientInfo.newClientId }, // 查询条件
                        { $set: { accountStatus: "掉线" } } // 更新操作
                    );
                    this.clients.delete(clientId); // 删除未存活的客户端
                    return clientInfo.ws.terminate(); // 关闭 WebSocket 连接
                }
                clientInfo.ws.isAlive = false; // 重置为 false，等待 pong
                clientInfo.ws.ping(); // 发送 ping
            });
        }, 30000); // 每30秒执行一次心跳检测
    } 
}

// 导出单例
module.exports = new WebSocketService();
